# -*- coding: utf-8 -*-
#
###
#
# Copyright (C) 2009 yed_ <yed (a) vanyli (o) net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
###

import sys

from ConfigParser import RawConfigParser
from os import mkdir, path
from gettext import gettext as _

class PyfuploadConfigHandler(RawConfigParser):
  '''config directory name'''
  dir_name = None

  '''full path to config directory'''
  dir_path = None

  '''config file'''
  file_name = 'config'

  '''full path to config file'''
  file_path = None

  '''parent object'''
  parent = None

  def __init__(self, parent, file=None):
    RawConfigParser.__init__(self)
    self.init_parent(parent)
    self.init_vars(file)
    self.init_fs()
    self.load_config()

  def init_parent(self, parent):
    if parent is None:
      print( _("Error during parent initialization") )
      sys.exit(0)
    self.parent = parent

  def init_vars(self, file):
    self.file_name = [file, self.file_name][not file]
    self.dir_name = '.' + self.parent.__project__
    self.dir_path = path.join(path.expanduser('~'), self.dir_name)
    self.file_path = path.join(self.dir_path, self.file_name)

  def init_fs(self):
    if not path.isdir(self.dir_path):
      try:
        mkdir(self.dir_path)
      except os.error:
        print( _('Error creating configuration directory'))
        sys.exit()
    [self._file_path, foo] = self.init_file(self.file_name)

  ''' return list, first element is file path, second if file was just created '''
  def init_file(self, file_name=None, touch=True):
    file_path = path.join(self.dir_path, file_name)
    if path.isfile(file_path):
      return [file_path, False]
    elif touch:
      try:
        open(file_path, 'w+').close()
        return [file_path, True]
      except Exception:
        print( _("Error while creating configuration file") + file_name)
        return [False, False]
    else:
      return [False, False]

  def load_config(self):
    self.read(self.file_path)

  def save_changes(self):
    fp = open(self.file_path, 'w')
    self.write(fp)
    fp.close()